package com.yxx.controller.admin;

import com.yxx.medicinecommon.constant.MessageConstant;
import com.yxx.medicinecommon.result.ResponseResult;
import com.yxx.medicinecommon.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.metrics.StartupStep;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.transform.Result;
import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口
 * 文件上传接口
 * @author yuxiangxun
 * @date 2024/9/12
 * @apiNote
 */
@Slf4j
@RequestMapping("/admin/common")
@RestController
@Api(tags = "通用接口")
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public ResponseResult<String> upload(MultipartFile file){
        try{
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //获取原始文件名的后缀
            String behind = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构建文件名
            String fileName =  UUID.randomUUID().toString() + behind;

            //文件请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), fileName);
            log.info("filePath:{}",filePath);
            return ResponseResult.success(fileName);

        }catch (IOException e){
            log.error("文件上传失败: {}",e);
        }

        return ResponseResult.error(MessageConstant.UPLOAD_FAILED);
    }
}
